# coding: utf-8
import os, time, random, string, platform, json, shutil, errno
from django.conf import settings
from  django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic import FormView
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext
from .models import DeployStatus, DeployPool
from .forms import UploadFileForm


def render_to_json_response(context, **response_kwargs):
    data = json.dumps(context)
    response_kwargs['content_type'] = 'application/json'
    return HttpResponse(data, **response_kwargs)


class DeployVersionUploadView(FormView):
    template_name = "deploy/upload_deployversion.html"
    form_class = UploadFileForm

    def form_invalid(self, form):
        # return self.render_to_response(RequestContext(self.request, {'form': form}))
        print('&'*10, form, '&'*10, sep='\n')
        return self.render_to_response(RequestContext(self.request, {'form': form}))

    def form_valid(self, form):
        current_user = self.request.user
        random_letter = ''.join(random.sample(string.ascii_uppercase, 2))
        deploy_version = time.strftime("%Y-%m%d-%H%M%S", time.localtime()) + random_letter
        description = form.cleaned_data['description']
        app_name = form.cleaned_data['app_name']
        is_inc_tot = form.cleaned_data['is_inc_tot']
        deploy_type = form.cleaned_data['deploy_type']
        file_path = form.cleaned_data['file_path']

        deployversion_upload_done(app_name, deploy_version, file_path)
        nginx_url = "{}/{}/{}".format(settings.NGINX_URL, app_name, deploy_version)
        DeployPool.objects.create(
            name=deploy_version,
            description=description,
            app_name=app_name,
            branch_build="upload",
            is_inc_tot=is_inc_tot,
            deploy_type=deploy_type,
            nginx_url=nginx_url,
            deploy_status=DeployStatus.objects.get(name='BUILD'),
            create_user=current_user,
        )
        return HttpResponseRedirect(reverse('deploy:list'))

    def get_success_url(self):
        return reverse_lazy('deploy:list')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['current_page_name'] = '新建发布单(上传)'
        return context


@csrf_exempt
def fileupload(request):
    files = request.FILES.getlist('files[]')
    file_name_list = []
    for f in files:
        if platform.system() == "Windows":
            destination = r'e:/tmp/'
        elif platform.system() == "Linux":
            destination = r'/tmp/'
        if not os.path.exists(destination):
            os.makedirs(destination)

        with open(os.path.join(destination, f.name), 'wb+') as destination:
            for chunk in f.chunks(chunk_size=10000):
                destination.write(chunk)
        file_name_list.append(f.name)
    return render_to_json_response(','.join(file_name_list))


def deployversion_upload_done(app_name, deploy_version, upload_file):
    if platform.system() == "Windows":
        src_file = os.path.join(r'e:/tmp/', upload_file)
        dest_folder = r'e:/oss_data/'
    elif platform.system() == "Linux":
        src_file = os.path.join(r'/tmp/', upload_file)
        dest_folder = os.path.join(r'/oss_data/', app_name, deploy_version)

    mkdir_p(dest_folder)
    dest_file = os.path.join(dest_folder, upload_file)
    shutil.move(src_file, dest_file)


def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise OSError
